package wxtools.demo.handler;

import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.soecode.wxtools.api.IService;
import com.soecode.wxtools.api.WxConsts;
import com.soecode.wxtools.api.WxMessageHandler;
import com.soecode.wxtools.bean.WxXmlMessage;
import com.soecode.wxtools.bean.WxXmlOutMessage;
import com.soecode.wxtools.bean.WxXmlOutNewsMessage.Item;
import com.soecode.wxtools.exception.WxErrorException;
import com.turing.util.Aes;
import com.turing.util.Md5;
import com.turing.util.PostServer;

/**
 * 示例：DemoHandler
 * 目的：返回用户 “恭喜你中奖了”
 * @author antgan
 * @date 2016/12/15
 *
 */
public class DemoHandler implements WxMessageHandler{

	@Override
	public WxXmlOutMessage handle(WxXmlMessage wxMessage, Map<String, Object> context, IService iService)
			throws WxErrorException {
		WxXmlOutMessage xmlOutMsg;
		if(WxConsts.EVT_SUBSCRIBE.equals(wxMessage.getEvent())){
			Item item=new Item();
			item.setDescription("这是测试数据");
			item.setPicUrl("http://pic1.5442.com/2015/0708/02/01.jpg");
			item.setTitle("测试");
			item.setUrl("http://114.115.208.201/demo/ck/pingjia.jsp?userName="+wxMessage.getFromUserName());
			xmlOutMsg=WxXmlOutMessage.NEWS().addArticle(item).toUser(wxMessage.getFromUserName()).fromUser(wxMessage.getToUserName()).build();
		}else{
			//必须以build()作为结尾，否则不生效。
			String ms=getHf(wxMessage.getContent());
			xmlOutMsg = WxXmlOutMessage.TEXT().content(ms).toUser(wxMessage.getFromUserName()).fromUser(wxMessage.getToUserName()).build();
		}
		return xmlOutMsg;
	}

	private String getHf(String content) {
		//图灵网站上的secret
		String secret = "7ae8ed6e844737c9";
		//图灵网站上的apiKey
		String apiKey = "dfd4407080fd480ca265489fdc54ff9f";
		String cmd = content;//测试用例
		//待加密的json数据
		String timestamp = String.valueOf(System.currentTimeMillis());
		//封装请求参数
		JSONObject json = new JSONObject();
		json.put("key", apiKey);
		json.put("timestamp", timestamp);
		json.put("info", cmd);
		//请求图灵api
		String result = PostServer.SendPost(json.toString(), "http://www.tuling123.com/openapi/api");
		JSONObject jobj=(JSONObject) JSONObject.parse(result);
		System.out.println("回复："+jobj.getString("text"));
		return jobj.getString("text");
	}
	
}
